package service

import (
	"encoding/binary"
	"fmt"
	"net"
)

// SendSvrd 发送数据到服务器
func SendSvrd(host string, port int, info []byte) error {
	addr := fmt.Sprintf("%s:%d", host, port)

	// 创建TCP连接
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		return fmt.Errorf("failed to connect to server: %w", err)
	}
	defer conn.Close()

	// 构建协议头：HRPC + version(1) + reserved(3) + length(4)
	header := make([]byte, 9)
	header[0] = 'H'
	header[1] = 'R'
	header[2] = 'P'
	header[3] = 'C'
	header[4] = 1
	// length字段占用header[5:9]的4个字节
	binary.BigEndian.PutUint32(header[5:9], uint32(len(info)))

	// 发送数据
	if _, err := conn.Write(header); err != nil {
		return fmt.Errorf("failed to write header: %w", err)
	}
	if _, err := conn.Write(info); err != nil {
		return fmt.Errorf("failed to write data: %w", err)
	}

	return nil
}

